<template>
  <div class="webview">
    <div class="canvasWrap">
      <!--<canvas id="canvas_bak" ref="canvas_bak" :style="{cursor:curcursor}"></canvas>-->
      <canvas id="canvas" ref="canvas" :style="{cursor:curcursor}"></canvas>
    </div>
    <div>
      <el-button @click="cancel">撤销</el-button>
      <el-button @click="next">返回</el-button>
      <el-button @click="clear">清空画布</el-button>
      <el-button size="small" @click="wy(1)">左移</el-button>
      <el-button size="small" @click="wy(2)">右移</el-button>
      <el-button size="small" @click="wy(3)">上移</el-button>
      <el-button size="small" @click="wy(4)">下移</el-button>
      <el-button size="small" @click="hb(1)">缩小</el-button>
      <el-button size="small" @click="hb(2)">放大</el-button>
      <el-button @click="switchPen(1)">铅笔</el-button>
      <el-button @click="switchPen(2)">毛笔</el-button>
      <el-button @click="switchPen(3)">橡皮擦</el-button>
      <div class="block">
        <span class="demonstration">线条粗细</span>
        <el-slider v-model="penSize"></el-slider>
      </div>
      <div class="block">
        <span class="demonstration">透明度</span>
        <el-slider v-model="penT"></el-slider>
      </div>
      <img
        crossorigin="anonymous"
        src="@/assets/img/pen2.png"
        class="active"
        id="pen2"
        alt
        style="display:none;"
      />
    </div>
  </div>
</template>

<script>
import $ from "jquery";
export default {
  data() {
    return {
      // 线条粗细
      penSize:10,
      // 透明度
      penT:0,
      // 毛笔效果要用的数组
      arr: [],
      has: [],
      // 笔触标识1是铅笔 2是毛笔
      penType: 1,
      // 缩放率
      scale: 1,
      // 起始横坐标
      left: 0,
      // 起开纵坐标
      top: 0,
      // 当前历史纪录索引
      cancelIndex: 0,
      // 橡皮擦笔触
      eraser:
        "url('') 3 24,  auto",
      // 铅笔笔触
      pen:
        "url('') 3 24,  auto",
      curcursor:"",
      // 撤销列表
      cancelList: [],
      // 是否能够画 就是说按下了以后才可以画
      canDraw: false,
      // 画布大小
      canvasSize: {
        width: 500,
        height: 500
      }
    };
  },
  mounted() {
    this.initCanvas();
    this.initDrag();
    this.initMb();
  },
  methods: {
    distance(a, b) {
      let x = b.x - a.x,
        y = b.y - a.y;
      return Math.sqrt(x * x + y * y);
    },
    initMb() {
      this.p = 0;
      this.l = 20;
      this.arr = [];
      this.moveFlag = false;
      this.upof = {};
      this.radius = 0;
      this.has = [];
      this.lineMax = 20;
      this.lineMin = 10;
      this.linePressure = 1;
      this.smoothness = 80;
      this.img = document.getElementById("pen2"); //默认笔刷
    },
    switchPen(type) {
      if (type == 1) {
        // 笔触改变为铅笔
        this.penType = 1;
        this.curcursor = this.pen
      }
      if (type == 2) {
        // 笔触改变为毛笔
        this.penType = 2;
        this.curcursor = this.pen
      }
      if (type == 3) {
        // 笔触改变为橡皮擦
        this.penType = 3;
        this.curcursor = this.eraser
      }
    },
    hb(type) {
      this.clear();
      let image = new Image();
      let index = this.cancelList.length - 1;
      let url = this.cancelList[index];
      image.src = url;
      image.onload = () => {
        if (type === 1) {
          // 缩小
          if (this.scale > 0) {
            this.scale = this.scale - 0.1;
          }
        }
        if (type === 2) {
          // 放大
          this.scale = this.scale + 0.1;
        }
        this.context.globalAlpha = 1
        this.context.drawImage(
          image,
          0,
          0,
          this.canvasSize.width,
          this.canvasSize.height,
          0,
          0,
          this.canvasSize.width * this.scale,
          this.canvasSize.height * this.scale
        );
        this.saveImageToAry();
      };
    },
    wy(type) {
      this.clear();
      let image = new Image();
      let index = this.cancelList.length - 1;
      let url = this.cancelList[index];
      image.src = url;
      image.onload = () => {
        if (type == 1) {
          // 左
          this.left = this.left - 10;
        }
        if (type == 2) {
          //  右
          this.left = this.left + 10;
        }
        if (type == 3) {
          //  上
          this.top = this.top - 10;
        }
        if (type == 4) {
          //  下
          this.top = this.top + 10;
        }
        this.context.globalAlpha = 1
        this.context.drawImage(
          image,
          0,
          0,
          this.canvasSize.width,
          this.canvasSize.height,
          this.left,
          this.top,
          this.canvasSize.width,
          this.canvasSize.height
        );
        this.saveImageToAry();
      };
    },
    // 清空画布
    clear() {
      this.context.globalAlpha = 1
      this.context.clearRect(
        0,
        0,
        this.canvasSize.width,
        this.canvasSize.height
      );
    },
    // 撤销
    cancel() {
      this.context.globalAlpha = 1
      this.cancelIndex++;
      this.clear();
      let image = new Image();
      let index = this.cancelList.length - 1 - this.cancelIndex;
      let url = this.cancelList[index];
      image.src = url;
      image.onload = () => {
        this.context.drawImage(
          image,
          0,
          0,
          image.width,
          image.height,
          0,
          0,
          this.canvasSize.width,
          this.canvasSize.height
        );
      };
    },
    // 返回
    next() {
      this.context.globalAlpha = 1
      this.cancelIndex--;
      this.clear();
      let image = new Image();
      let index = this.cancelList.length - 1 - this.cancelIndex;
      let url = this.cancelList[index];
      image.src = url;
      image.onload = () => {
        this.context.drawImage(
          image,
          0,
          0,
          image.width,
          image.height,
          0,
          0,
          this.canvasSize.width,
          this.canvasSize.height
        );
      };
    },
    downEvent(e) {
      this.canDraw = true;
      this.context.strokeStyle = "#0000ff";
      this.context.lineWidth = this.penSize/2;
      this.context.globalAlpha = 1 - this.penT / 100;
      e = e || window.event;
      let startX = e.offsetX || e.touches[0].pageX;
      let startY = e.offsetY || e.touches[0].pageY;
      // 铅笔
      if (this.penType === 1) {
        this.context.beginPath();
      }
      //毛笔
      if (this.penType === 2) {
        this.has = [];
        this.upof = {
          x: startX,
          y: startY
        };
        // this.ctx.drawImage(this.img,(this.upof.x - this.big/2),(this.upof.y - this.big/2),this.big,this.big);
        let x1 = this.upof.x;
        let y1 = this.upof.y;
        this.arr.unshift({ x1, y1 });
      }
      //橡皮擦
      if (this.penType === 3) {
        this.context.clearRect(
          startX,
          startY,
          20,
          20
        );
      }
    },
    moveEvent(e) {
      let startX =  e.offsetX || e.touches[0].pageX;
      let startY =  e.offsetY || e.touches[0].pageY;
      let x = startX
      let y = startY
      if (this.canDraw) {
        // 铅笔
        if (this.penType === 1) {
          this.context.lineTo(startX + 2, startY + 2);
          this.context.stroke();
        }
        //毛笔
        if (this.penType === 2) {
          let of = {
            x: startX,
            y: startY
          };
          let up = this.upof; //down
          let ur = this.radius; //banjing
          let b = 0;
          this.has.unshift({
            time: new Date().getTime(),
            dis: this.distance(up, of)
          });
          let dis = 0;
          let time = 0;
          for (var n = 0; n < this.has.length - 1; n++) {
            dis += this.has[n].dis;
            time += this.has[n].time - this.has[n + 1].time;
            if (dis > this.smoothness) break;
          }
          let or =
            Math.min(
              (time / dis) * this.linePressure + this.lineMin,
              this.lineMax
            ) / 2;
          this.radius = or;
          this.upof = of;
          var len = Math.round(this.has[0].dis / 2) + 1;
          for (let i = 0; i < len; i++) {
            let x = up.x + ((of.x - up.x) / len) * i;
            let y = up.y + ((of.y - up.y) / len) * i;
            let r = ur + ((or - ur) / len) * i;
            this.context.beginPath();
            let r_r = r * 2;
            x = x - this.l / 2;
            y = y - this.l / 2;
            this.arr.unshift({ x, y });
            this.context.drawImage(this.img, x, y, this.penSize/5+20, this.penSize/5+20);
            this.l = this.l - 0.2;
            if (this.l < 10) this.l = 10;
            this.p++;
          }
        }
        // 橡皮擦
        if (this.penType === 3){
          this.context.clearRect(
            startX,
            startY,
            10,
            10
          );
        }
      }
    },
    //保存历史 用于撤销
    saveImageToAry() {
      this.cancelIndex = 0;
      this.left = 0;
      this.top = 0;
      this.scale = 1;
      let dataUrl = this.canvas.toDataURL();
      this.cancelList.push(dataUrl);
    },
    upEvent(e) {
      this.canDraw = false;
      // 毛笔
      if (this.penType == 2) {
        this.l = 20;
        if (this.arr.length > 100) {
          for (var j = 0; j < 60; j++) {
            this.arr[j].x = this.arr[j].x - this.l / 4;
            this.arr[j].y = this.arr[j].y - this.l / 4;
            this.context.drawImage(
              this.img,
              this.arr[j].x,
              this.arr[j].y,
              this.l,
              this.l
            );

            this.l = this.l - 0.3;
            if (this.l < 5) this.l = 5;
          }
          this.l = 20;
          this.arr = [];
        }
        if (this.arr.length == 1) {
          this.context.drawImage(
            this.img,
            this.arr[0].x1 - this.l / 2,
            this.arr[0].y1 - this.l / 2,
            this.l,
            this.l
          );
          this.arr = [];
        }
      }
      this.saveImageToAry();
    },
    leaveEvent(e) {
      if (this.canDraw) {
        this.canDraw = false;
        this.saveImageToAry();
      }
    },
    // 初始化画布
    initCanvas() {
      this.curcursor = this.pen
      this.canvas = document.getElementById("canvas");
      this.canvas.width = this.canvasSize.width;
      this.canvas.height = this.canvasSize.height;
      this.context = this.canvas.getContext("2d");

      // this.canvas_bak = document.getElementById("canvas_bak");
      // this.canvas_bak.width = this.canvasSize.width;
      // this.canvas_bak.height = this.canvasSize.height;
      // this.context_bak = this.canvas.getContext("2d");
    },
    //初始化拖入效果
    initDrag() {
      //鼠标场景--电脑端.
      this.canvas.onmousedown = this.downEvent.bind(this)
      this.canvas.onmousemove = this.moveEvent.bind(this)
      this.canvas.onmouseup = this.upEvent.bind(this)
      this.canvas.onmouseleave = this.leaveEvent.bind(this)
      //触摸场景--手机端/触摸屏机
      this.canvas.addEventListener(
        "touchstart",
        this.downEvent.bind(this),
        false
      );
      this.canvas.addEventListener(
        "touchmove",
        this.moveEvent.bind(this),
        false
      );
      this.canvas.addEventListener(
        "touchleave",
        this.leaveEvent.bind(this),
        false
      );
      this.canvas.addEventListener("touchend", this.upEvent.bind(this), false);
    }
  }
};
</script>

<style lang="scss" scoped>
.webview {
  .canvasWrap {
    width: 500px;
    height: 500px;
    background: red;
    position:relative;
  }
  canvas{
    position:absolute;
    left:0;
    top:0;
    width:100%;
    height:100%;
  }
  .block{
    width:400px;
  }
}
</style>
